
import axios, { AxiosResponse, } from 'axios';
import type { AxiosInstance, AxiosRequestConfig,AxiosError } from 'axios'
import type {
  RequestConfig,
  RequestInterceptors,
	ApiResponse,
	ApiRequest
} from './types'
import { showMessage } from "./status";   // 引入状态码文件
import {Notify,Loading} from 'vant'

class Request{
	static axios(arg0: { url: string; method: string; options: any; }) {
		throw new Error('Method not implemented.');
	}
	static get() {
		throw new Error('Method not implemented.');
	}
	readonly baseURL: string|undefined|boolean;
	public timeout: number;
	// axios 实例
  instance!: AxiosInstance;
	 // 拦截器对象
	interceptorsObj?: RequestInterceptors
	constructor(config:RequestConfig){
		this.baseURL = import.meta.env.VITE_AXIOSURL
		this.timeout = 30000; //30s请求超时
		this.interceptorsObj = config.interceptors
	}
	//请求拦截
	setInterceptors(instance:any){
	
		// 使用实例拦截器
    instance.interceptors.request.use(
      this.interceptorsObj?.requestInterceptors,
      this.interceptorsObj?.requestInterceptorsCatch,
    )
    instance.interceptors.response.use(
      this.interceptorsObj?.responseInterceptors,
      this.interceptorsObj?.responseInterceptorsCatch,
    )
		//请求
		instance.interceptors.request.use( (config: AxiosRequestConfig) =>{
			config.headers = {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',        // 传参方式
				'Accept': 'application/json'
			}
			//获取sessionsId 没有就调整登录页
			// if (token) { // 携带token
			// 	config.headers.Authorization = `Bearer ${token}`
			// }
			return config
		}, (error: any) =>{
			return Promise.reject(error)
		});
	
		//响应
		instance.interceptors.response.use((res:AxiosResponse)=>{
			const { code, message } = res.data
			if(code==200){
				return Promise.resolve(res.data.data)
			}else{
				// 错误提示
				// Notify.error(message)
				return Promise.reject(res.data.data)
			}
		},(error:AxiosError)=>{
			const res = error?.response
			// if (res && res.status === 401) { // 未登录 token失效
			// 	store.dispatch('user/resetToken').then(() => {
			// 		window.location.reload()
			// 	})
			// }
			let message =	showMessage(res.status); 
			Notify({ type: 'danger', message: message});
			return Promise.reject(error)


		
		})
	}
	mergeOptions(options:any){
		return {baseURL: this.baseURL,timeout:this.timeout, ...options}
	}
	request<T>(options:T){
		this.instance = axios.create()
		this.setInterceptors(this.instance);
		const opts = this.mergeOptions(options);
		return this.instance(opts)
	}
	// axios<T>(obj:T){
	// 	return this.request<T>(obj)
	// }
}

export default Request;
